<!--
 * @Descripttion: 生成二维码组件
 * @version: 1.0
 * @Author: sakuya
 * @Date: 2021年12月20日14:22:20
 * @LastEditors:
 * @LastEditTime:
-->

<template>
	<div ref="qrContainer" :style="{ width: size + 'px', height: size + 'px' }">
		<canvas ref="qrCanvas" :width="size" :height="size"></canvas>
	</div>
</template>

<script>
import QRCode from 'qrcode'

export default {
	props: {
		text: { type: String, required: true, default: "" },
		size: { type: Number, default: 100 },
		logo: { type: String, default: "" },
		logoSize: { type: Number, default: 30 },
		logoPadding: { type: Number, default: 5 },
		colorDark: { type: String, default: "#000000" },
		colorLight: { type: String, default: "#ffffff" },
		correctLevel: { type: Number, default: 2 },
	},
	data() {
		return {
			qrcode: null
		}
	},
	watch: {
		text() {
			this.draw()
		}
	},
	mounted() {
		this.draw()
	},
	methods: {
		// 创建二维码
		async generateQR() {
			try {
				const canvas = this.$refs.qrCanvas
				await QRCode.toCanvas(canvas, this.text, {
					width: this.size,
					height: this.size,
					color: {
						dark: this.colorDark,
						light: this.colorLight
					},
					errorCorrectionLevel: this.getErrorCorrectionLevel()
				})
			} catch (error) {
				console.error('Error generating QR code:', error)
			}
		},
		
		// 绘制LOGO
		async drawLogo() {
			return new Promise((resolve, reject) => {
				if (!this.logo) {
					resolve()
					return
				}
				
				const canvas = this.$refs.qrCanvas
				const ctx = canvas.getContext('2d')
				const logo = new Image()
				
				logo.onload = () => {
					const logoPos = (this.size - this.logoSize) / 2
					const rectSize = this.logoSize + this.logoPadding
					const rectPos = (this.size - rectSize) / 2
					
					// 绘制白色背景
					ctx.fillStyle = this.colorLight
					ctx.fillRect(rectPos, rectPos, rectSize, rectSize)
					
					// 绘制LOGO
					ctx.drawImage(logo, logoPos, logoPos, this.logoSize, this.logoSize)
					resolve()
				}
				
				logo.onerror = () => {
					console.warn('Failed to load logo image:', this.logo)
					resolve() // 即使 LOGO 加载失败也继续
				}
				
				logo.crossOrigin = 'anonymous'
				logo.src = this.logo
			})
		},
		
		// 获取错误纠正级别
		getErrorCorrectionLevel() {
			const levels = ['L', 'M', 'Q', 'H']
			return levels[this.correctLevel] || 'M'
		},
		
		// 绘制二维码
		async draw() {
			await this.generateQR()
			if (this.logo) {
				await this.drawLogo()
			}
		}
	}
}
</script>

<style scoped>
canvas {
	display: block;
	border-radius: 4px;
}
</style>
